import {
  HttpException,
  HttpStatus,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { UserService } from '@/modules/user/user.service';
import { JwtService } from '@nestjs/jwt';
import { CreateUserDto } from '@/modules/user/create-user.dto';
import { User } from '@/modules/user/user.entity';
import argon2d from 'argon2';

@Injectable()
export class AuthService {
  constructor(
    private userService: UserService,
    private jwtService: JwtService,
  ) {}

  async login(username: string, password: string) {
    // 校验用户密码
    const user = await this.userService.findByUsername(username);
    if (!user) {
      throw new HttpException('该用户不存在', HttpStatus.NOT_FOUND);
    }
    const bool = await argon2d.verify(user.password, password);
    if (!bool) {
      throw new UnauthorizedException('密码不匹配');
    }
    // 生成jwtToken
    const payload = { username, userid: user.id };
    return {
      token: await this.jwtService.signAsync(payload),
    };
  }

  async signup(username: string, password: string) {
    if (!username || !password) {
      throw new HttpException('用户名或者密码不能为空', HttpStatus.BAD_REQUEST);
    }
    const user: CreateUserDto = new User();
    user.username = username;
    user.password = await argon2d.hash(password); // 对用户密码使用argon2 加密
    // user.role = '';
    user.nickname = '';
    user.avatar = '';
    user.active = 1;
    console.log('user', user);
    return this.userService.create(user);
  }
}
